# -*- coding: utf-8 -*-
"""
Created on
@Time: 2024/12/20 11:39
@Author: Mr.Z
@contact: <QQ:40061980>
@contact: bob@pheks.com
@File: send_email.py
@IDE: PyCharm
@Python Version：
"""

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

from utils import log_recorder

# 调用日志记录模块
logger = log_recorder.setup_logger()


# 解密函数，需要将加密后的密码和key解码后传入
# 这里的key是加密密钥，需要和加密时使用的key保持一致
def decrypt_password(ciphertext, key):
    iv = ciphertext[:AES.block_size]  # 提取iv
    ct = ciphertext[AES.block_size:]  # 提取密文
    cipher = AES.new(key, AES.MODE_CBC, iv)  # 创建一个新的AES对象
    pt = unpad(cipher.decrypt(ct), AES.block_size)  # 解密密文
    return pt.decode('utf-8')  # 返回解密后的密码


def send_mail(mail_info, mail_text):
    """发送邮件函数，从数据库中获取信息"""
    # 从setting.py中获取信息
    from_addr = mail_info['from_addr']  # 发送者邮箱
    to_addr = mail_info['to_addr']  # 接收者邮箱
    subject = mail_text['subject']  # 邮件主题
    image_path = mail_info.get('image_path', None)  # 使用get方法避免keyError

    text = mail_text['message']  # 邮件正文，可以是字符串或HTML代码，需要从字典中获取

    smtp_server = mail_info['smtp_server']  # 邮箱服务器，从字典中获取
    smtp_port = mail_info['smtp_port']  # 邮箱服务器端口，从字典中获取

    # 从字典中获取加密后的16进制密码，并将其转换为bytes类型（解码）
    # smtp_password = bytes.fromhex(mail_info['smtp_password'])
    smtp_password = mail_info['smtp_password']

    # 从字典中获取加密后的16进制key，并将其转换为bytes类型（解码）
    # key = bytes.fromhex(mail_info['key'])

    # 解密密码，调用解密函数
    # real_password = decrypt_password(smtp_password, key)

    # 创建一个带附件的实例
    msg = MIMEMultipart()
    # 邮件主题
    msg['Subject'] = subject
    # 发送者
    msg['From'] = from_addr
    # 接收者
    msg['To'] = to_addr
    # 邮件正文
    msg.attach(MIMEText(text, 'plain'))
    # 附件
    if image_path:
        with open(image_path, 'rb') as f:
            img = MIMEImage(f.read())
            img.add_header('Content-Disposition', 'attachment', filename=image_path.split('/')[-1])
            msg.attach(img)

    # 发送邮件
    try:
        smtp_obj = smtplib.SMTP_SSL(smtp_server, smtp_port)  # 连接服务器
        logger.info('[send_mail]-连接邮箱服务器成功')
        # smtp_obj.set_debuglevel(1)  # 打印出和SMTP服务器交互的所有信息
        # smtp_obj.login(from_addr, real_password)  # 登录服务器
        smtp_obj.login(from_addr, smtp_password)  # 登录服务器
        logger.debug('[send_mail]-登录邮箱服务器成功')
        smtp_obj.sendmail(from_addr, to_addr.split(','), msg.as_string())  # 发送邮件
        logger.info('[send_mail]-邮件发送成功')
    except smtplib.SMTPException as e:
        # print('邮件发送失败', e)
        logger.error('[send_mail]-邮件发送失败：{}'.format(e))
    finally:
        smtp_obj.quit()  # 关闭连接
        logger.info('[send_mail]-邮箱服务器连接已关闭')


# if __name__ == '__main__':
    # 测试文件下载成功时
    # send_mail(setting.main_info, mail_success_info)

    # 测试文件下载失败时
    # send_mail(setting.main_info, mail_fail_info)
